<?php
class HttpClient{
    public function __construct($url=null){
        if(isset($url)){
            $this->setUrl($url);
        }
    }
    protected $url;
    protected $method;
    protected $args;
    protected $status;
    
    protected $contents;
    protected $cRs;
    protected $info;
    
    /*
    $info 将包含以下信息：
 "url" 
 "content_type" 
 "http_code" 
 "header_size" 
 "request_size" 
 "filetime" 
 "ssl_verify_result" 
 "redirect_count" 
 "total_time" 
 "namelookup_time" 
 "connect_time" 
 "pretransfer_time" 
 "size_upload" 
 "size_download" 
 "speed_download" 
 "speed_upload" 
 "download_content_length" 
 "upload_content_length" 
 "starttransfer_time" 
 "redirect_time" 
    */
    
    private $methodMap=array(
        "get"=>CURLOPT_HTTPGET,
        "post"=>CURLOPT_POST
                             );
    
    protected function initCurl(){
        //网址设置
        $this->cRs=curl_init($this->url);
        if($this->cRs===false){
            throw new Exception("Error on init url:{$this->url}");
        }
        //方法设置
        $opt=$this->methodMap[$this->method];
        curl_setopt($this->cRs,$opt,1);
        
        //参数设置
        if($this->method=="post"){
            if(is_array($this->args)){
                $argList=array();
                //参数转换
                foreach($this->args as $key=>$value){
                    $argList[]=$key."=".urlencode($value);
                }
                $this->args=implode("&",$argList);
            }
            curl_setopt($this->cRs,CURLOPT_POSTFIELDS,$this->args);
        }
        //获取返回结果
        curl_setopt($this->cRs, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($this->cRs, CURLOPT_FAILONERROR, 1);

        return $this;
    }
    
    public function setUrl($url){
        $this->url=$url;
        return $this;
    }
    public function setMethod($method){
        $method=strtolower($method);
        $this->method=$method;
        return $this;
    }
    
    public function setArgs($args){
        $this->args=$args;
        return $this;
    }
    
    public function resetState(){
        $this->args="";
        $this->status="";
        $this->contents="";
        $this->cRs=null;
    }
    
    public function send(){
        $this->initCurl();
        $this->contents=curl_exec($this->cRs);
        $this->info=curl_getinfo($this->cRs);
        curl_close($this->cRs);
    }
    public function getHttpCode(){
        return $this->info["http_code"];
    }
    public function getContent(){
        return $this->contents;
    }
    
    public function post($data=null){
        $this->setMethod("POST");
        if(!empty($data)){
            $this->setArgs($data);
        }
        $this->send();
        return $this->getContent();
    }
    public function get(){
        $this->setMethod("GET");
        if(!empty($data)){
            $this->setArgs($data);
        }
        $this->send();
        return $this->getContent();
    }
}